package com.sunwayhorizo.health.hl7.rim;

import java.io.*;
import java.sql.*;
import java.util.*;
import java.util.Date;
import javax.persistence.*;
import org.jboss.seam.annotations.*;
import com.sunwayhorizo.health.common.*;
import com.sunwayhorizo.health.hl7.common.*;
import com.sunwayhorizo.health.hl7.datatypes.*;
import com.sunwayhorizo.health.hl7.datatypes.common.*;
import com.sunwayhorizo.health.hl7.factories.*;
import com.sunwayhorizo.health.hl7.persistent.*;

import static com.sunwayhorizo.health.hl7.vocabulary.EntityCdSetCode.*;

import com.sunwayhorizo.health.hl7.vocabulary.*;

@Name("Hl7Entity")
@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorValue("ENT")
public class Hl7Entity extends RimCoreEntities implements Serializable
{

    /*
     * public CS classCode; public CS determinerCode; public SET_II id; public
     * CE code; public SET_PQ quantity; public BAG_EN name; public ED desc;
     * public IVL_TS existenceTime; public BAG_TEL telecom; public CE riskCode;
     * public CE handlingCode; public Iterator languageCommunication; public
     * Iterator ownedPlayedRoles; public Iterator OwnedScopedRoles; public
     * Iterator playedRoles; public Iterator ScopedRoles;
     */
    // Entity ������

    // @Transient
    // public CS statusCode; //状态代码

    /**
     * 
     */
    private static final long serialVersionUID = 1L;


    public Hl7Entity() throws Hl7Exception
    {
        DataTypeUtil.initialize();
    }


    public Hl7Entity(ReferenceModifier referencemodifier)
    {
        super(referencemodifier);
    }


    public void setDeterminerCode(CS determinerCode)
    {
        this.setDmCode(determinerCode.code().toString());
    }


    public CS getDeterminerCode() throws Hl7Exception
    {
        return DataTypeUtil.getCS(this.getDmCode());
    }


    /**
     * 
     * @param quantity
     */
    public void setQuantity(SET_PQ quantity)
    {
        PQImpl pq = (PQImpl) quantity.toSet().iterator().next();
        List<RimCoreEntyQtys> entyQtys = this.getEntyQtysList();
        if(ListUtil.isNotEmpty(entyQtys))
        {
            for(int i=0; i<entyQtys.size(); i++)
            {
                RimCoreEntyQtys entyQty = entyQtys.get(i);
                entyQty.setValueNumTxt(pq.value().toString());
                entyQty.setValueUomCode(pq.unit().toString());
            }
        }
        else
        {
            newQuantity(quantity);
        }
    }
    
    public void newQuantity(SET_PQ quantity)
    {
        PQImpl pq = (PQImpl) quantity.toSet().iterator().next();
        RimCoreEntyQtys entyQtys = new RimCoreEntyQtys();
        entyQtys.setValueNumTxt(pq.value().toString());
        entyQtys.setValueUomCode(pq.unit().toString());
        this.addEntyQtys(entyQtys);
    }


    public SET_PQ getQuantity() throws Hl7Exception
    {
        if(ListUtil.isEmpty(this.getEntyQtysList()) && this.getEntyQtysList().get(0) == null) return null;
        RimCoreEntyQtys entyQtys = (RimCoreEntyQtys) this.getEntyQtysList().get(0);
        return DataTypeUtil.getSET_PQ((entyQtys.getValueNumTxt() == null ? "" : entyQtys.getValueNumTxt()), (entyQtys.getValueUomCode() == null ? "" : entyQtys.getValueUomCode()));
    }


    /**
     * 设置Hl7Entity的id值
     * 
     * @param id
     *            Hl7Entity的唯一性约束
     */
    public void setId(II id)
    {
        String identifierName = id.identifierName().stringValue();
        if (StrUtil.isEmpty(identifierName))
        {
            return;
        }
        setId(id, EntityIICode.valueOf(identifierName));
    }


    // 添加名字
    @SuppressWarnings("rawtypes")
    private void newName(BAG_EN name)
    {
        List mList = name.toList();
        for (int i = 0; i < mList.size(); i++)
        {
            ENImpl en = (ENImpl) mList.get(i);
            RimCoreEntyNames entyNames = new RimCoreEntyNames();
            // 生成名称全称
            entyNames.setFormatted(en.formatted().toString());
            // 生成USECODE
            entyNames.setEntyNameUses(en.use().toSet());
            // 生成名称的各个部分
            entyNames.setEntyNameParts(en.toList());

            this.addEntyNames(entyNames);
        }
    }


    /**
     * 设置Hl7Entity Name属性 所有的继承于Hl7Entity的实体添加修改Name都用次方法
     * 该方法只支持RimCoreEntyNames与NameParts，NameUses一对一的添加修改
     * 多对多的关系后续在完善（多对多外国人姓名不支持）
     * 
     * @param name
     *            需要添加修改的Name
     */
    @SuppressWarnings("rawtypes")
    public void setName(BAG_EN name)
    {
        List mList = name.toList();
        ENImpl en = (ENImpl) mList.get(0);
        Set set = (Set) en.use().toSet();
        CSImpl use = (CSImpl) set.iterator().next();
        String code = use.code().toString();

        List<RimCoreEntyNames> list = getEntyNamesList();
        if (ListUtil.isNotEmpty(list))
        {
            boolean b = true;
            for (int j = 0; j < list.size(); j++)
            {
                RimCoreEntyNames entyNames = (RimCoreEntyNames) list.get(j);
                List<RimCoreEntyNameUses> useNames = entyNames.getEntyNameUsesList();
                RimCoreEntyNameUses nameuser = (RimCoreEntyNameUses) useNames.get(0);
                if (code.equals(nameuser.getUse()))
                {
                    entyNames.setFormatted(en.formatted().toString());
                    entyNames.getEntyNamePartsList().get(0).setLiteral(en.formatted().toString());
                    b = false;
                    break;
                }
            }
            if (b)
            {
                newName(name);
            }
        }
        else
        {
            newName(name);
        }
    }


    /**
     * 得到Hl7Entity 的Name
     * 
     * @return BAG_EN
     * @throws Hl7Exception
     */
    @SuppressWarnings("rawtypes")
    public BAG_EN getName() throws Hl7Exception
    {
        List mList = this.getEntyNamesList();
        int size = mList.size();
        String name[][] = new String[size][];
        String typeCode[][] = new String[size][];
        String useCode[] = new String[size];

        for (int i = 0; i < size; i++)
        {
            RimCoreEntyNames entyNames = (RimCoreEntyNames) mList.get(i);
            List mmList = entyNames.getEntyNamePartsList();
            int size1 = mmList.size();
            name[i] = new String[size1];
            typeCode[i] = new String[size1];
            for (int j = 0; j < size1; j++)
            {
                RimCoreEntyNameParts partName = (RimCoreEntyNameParts) mmList.get(j);
                name[i][j] = partName.getLiteral();
                typeCode[i][j] = partName.getPartType();
            }

            List mmmList = entyNames.getEntyNameUsesList();
            RimCoreEntyNameUses nameUses = null;
            for (int k = 0; k < mmmList.size(); k++)
            {
                nameUses = (RimCoreEntyNameUses) mmmList.get(k);
            }
            useCode[i] = (nameUses != null ? nameUses.getUse() : "");
        }
        return DataTypeUtil.getBagEN(name, typeCode, useCode);
    }


    /**
     * 获得指定的name
     * 
     * @param useCode
     * @return EN
     * @throws Hl7Exception
     * 
     */
    public EN getNameByUse(CS useCode) throws Hl7Exception
    {

        for (RimCoreEntyNames name : getEntyNamesList())
        {
            for (RimCoreEntyNameUses use : name.getEntyNameUsesList())
            {
                if (use.getUse().equals(useCode.code().stringValue()))
                {
                    return DataTypeUtil.getEN(DataTypeUtil.getST(name.getFormatted()), DataTypeUtil.getCS(use.getUse()));
                }
            }
        }

        return null;
    }


    public void setDesc(ED desc)
    {
        RimCoreEds ed = this.getRimCoreEdsDescEdId();
        ed = converRimCoreEds(ed, desc);
        this.setRimCoreEdsDescEdId(ed);
    }


    public ED getDesc() throws Hl7Exception
    {
        RimCoreEds ed = this.getRimCoreEdsDescEdId();
        if (ed != null)
        {
            return DataTypeUtil.getED(ed.getEdClob() != null ? String.valueOf(ed.getEdClob()) : null, ed.getEdBlob());
        }
        else
        {
            return DataTypeFactory.getInstance().nullED(DataTypeUtil.getCS(""));
        }
    }


    public void setExistenceTime(IVL_TS existenceTime)
    {
        this.setExistenceStartDateTs(new Timestamp(existenceTime.low().toDate().getTime()));
        this.setExistenceEndDateTs(new Timestamp(existenceTime.high().toDate().getTime()));
        this.setExistenceDateTxt(existenceTime.literal().toString());
        PQ pq = (PQ) existenceTime.width();
        this.setExistenceDateIvlTxt(pq.value().literal().toString());
        this.setExistenceDateIvlUomCode(pq.unit().code().toString());
    }


    public IVL_TS getIVL_TS() throws Hl7Exception
    {
        return DataTypeUtil.getIVL_TS(this.getExistenceStartDateTs(), this.getExistenceEndDateTs(), this.getExistenceDateIvlTxt(),
            this.getExistenceDateIvlUomCode(), null);
    }


    // 保存电话list信息
    @SuppressWarnings({ "rawtypes" })
    private void newTelecomList(BAG_TEL telecom)
    {
        List mList = telecom.toList();
        for (int i = 0; i < mList.size(); i++)
        {
            TELImpl tel = (TELImpl) mList.get(i);
            newTelecom(tel);
        }
    }


    // 保存一个电话信息
    private void newTelecom(TELImpl tel)
    {
        RimCoreEntyTelAddrs entyTelAddrs = new RimCoreEntyTelAddrs();
        entyTelAddrs.setAddress(tel.address().toString());
        entyTelAddrs.setScheme(tel.scheme().toString());
        entyTelAddrs.setEffectiveStartDateTs(new Timestamp(tel.useablePeriod().hull().low().toDate().getTime()));
        entyTelAddrs.setEffectiveEndDateTs(new Timestamp(tel.useablePeriod().hull().high().toDate().getTime()));
        entyTelAddrs.setEffectiveGtsTxt(tel.useablePeriod().literal().toString());
        entyTelAddrs.setEntyTelAddrUses(tel.use().toSet());
        this.addEntyTelAddrs(entyTelAddrs);
    }


    /**
     * 设置电话属性 所有继承与Hl7Entity 的实体添加，修改都用此方法
     * 
     * @param telecom
     *            电话信息
     */
    @SuppressWarnings("rawtypes")
    public void setTelecom(BAG_TEL telecom)
    {
        List mList = telecom.toList();
        for (int j = 0; j < mList.size(); j++)
        {
            TELImpl tel = (TELImpl) mList.get(j);
            CSImpl useCode = (CSImpl) tel.use().toSet().iterator().next();
            String newUse = useCode.code().toString();
            List<RimCoreEntyTelAddrs> listTelAddrs = this.getEntyTelAddrsList();
            if (ListUtil.isNotEmpty(listTelAddrs))
            {
                if (listTelAddrs.size() > j)
                {
//                    RimCoreEntyTelAddrs telAddr = (RimCoreEntyTelAddrs) listTelAddrs.get(j);
//                    String oldUse = telAddr.getEntyTelUsesList().get(0).getUse();
//                    if (oldUse.equals(newUse))
//                    {
//                        // 修改原来的值
//                        telAddr.setAddress(tel.address().toString());
//                        telAddr.setScheme(tel.scheme().toString());
//                        telAddr.setEffectiveStartDateTs(new Timestamp(tel.useablePeriod().hull().low().toDate().getTime()));
//                        telAddr.setEffectiveEndDateTs(new Timestamp(tel.useablePeriod().hull().high().toDate().getTime()));
//                        telAddr.setEffectiveGtsTxt(tel.useablePeriod().literal().toString());
//                    }
//                    else
//                    {
//                        for(int i=0; i<listTelAddrs.size(); i++)
//                        {
//                            RimCoreEntyTelAddrs oldTelAddr = (RimCoreEntyTelAddrs) listTelAddrs.get(i);
//                            String oldUse1 = oldTelAddr.getEntyTelUsesList().get(0).getUse();
//                            if (oldUse1.equals(newUse))
//                            {
//                                // 修改原来的值
//                                telAddr.setAddress(tel.address().toString());
//                                telAddr.setScheme(tel.scheme().toString());
//                                telAddr.setEffectiveStartDateTs(new Timestamp(tel.useablePeriod().hull().low().toDate().getTime()));
//                                telAddr.setEffectiveEndDateTs(new Timestamp(tel.useablePeriod().hull().high().toDate().getTime()));
//                                telAddr.setEffectiveGtsTxt(tel.useablePeriod().literal().toString());
//                            }
//                        }
//                    }
                    for(int i=0; i<listTelAddrs.size(); i++)
                    {
                        RimCoreEntyTelAddrs oldTelAddr = (RimCoreEntyTelAddrs) listTelAddrs.get(i);
                        String oldUse1 = oldTelAddr.getEntyTelUsesList().get(0).getUse();
                        if (oldUse1.equals(newUse))
                        {
                            // 修改原来的值
                            oldTelAddr.setAddress(tel.address().toString());
                            oldTelAddr.setScheme(tel.scheme().toString());
                            oldTelAddr.setEffectiveStartDateTs(new Timestamp(tel.useablePeriod().hull().low().toDate().getTime()));
                            oldTelAddr.setEffectiveEndDateTs(new Timestamp(tel.useablePeriod().hull().high().toDate().getTime()));
                            oldTelAddr.setEffectiveGtsTxt(tel.useablePeriod().literal().toString());
                            break;
                        }
                    }
                }
                // 当数据库的值比新加的值少时候单独保存值
                if (listTelAddrs.size() <= j)
                {
                    newTelecom(tel);
                }
            }
            else
            {
                newTelecomList(telecom);
            }
        }
    }


    /**
     * 得到电话集合
     * 
     * @return BAG_TEL
     * @throws Hl7Exception
     */
    @SuppressWarnings("rawtypes")
    public BAG_TEL getTelecom() throws Hl7Exception
    {

        List mList = this.getEntyTelAddrsList();
        int size = mList.size();
        String scheme[] = new String[size];
        String address[] = new String[size];
        String telUseCode[] = new String[size];
        Date useablePeriod[][] = new Date[size][2];
        for (int i = 0; i < size; i++)
        {
            RimCoreEntyTelAddrs entyTelAddrs = (RimCoreEntyTelAddrs) mList.get(i);
            scheme[i] = entyTelAddrs.getScheme();
            address[i] = entyTelAddrs.getAddress();
            useablePeriod[i][0] = entyTelAddrs.getEffectiveStartDateTs();
            useablePeriod[i][1] = entyTelAddrs.getEffectiveEndDateTs();

            List mmList = entyTelAddrs.getEntyTelUsesList();
            RimCoreEntyTelUses entyTelUses = (RimCoreEntyTelUses) mmList.get(0);
            telUseCode[i] = entyTelUses.getUse();
        }

        return DataTypeUtil.getBAG_TEL(scheme, address, useablePeriod, telUseCode);
    }


    /**
     * @param riskCode
     */
    public void setRiskCode(CE ce)
    {
        if (null != ce && ce.codeSystemEnName() != null && ce.codeName() != null)
        {
            setRimCoreEntyCdSets(ce, RISKCODE);
        }
        else
        {
            if(StrUtil.isNotEmpty(ce.code().toString()) && !ce.code().toString().equals("<Null:NullFlavor: NI>"))
            {
                this.setRiskCodeEtsId(ce.code().toString());
            }
        }
    }


    public CE getRiskCode() throws Hl7Exception
    {
        if (this.getRiskCodeEtsId().equals(RISKCODE.toString()))
        {
            for (RimCoreEntyCdSets entityCdSets : this.getEntyCdSetsList())
            {
                if (this.getRiskCodeEtsId().equals(entityCdSets.getAttributeTypeCode()))
                {
                    return DataTypeUtil.getCE(entityCdSets);
                }
            }
        }
        else
            return DataTypeUtil.getCE(this.getRiskCodeEtsId());
        return null;
    }


    /**
     * @param handlingCode
     */
    public void setHandlingCode(CE ce)
    {
        if (null != ce && ce.codeSystemEnName() != null && ce.codeName() != null)
        {
            setRimCoreEntyCdSets(ce, HANDLINGCODE);
        }
        else
        {
            if(StrUtil.isNotEmpty(ce.code().toString()) && !ce.code().toString().equals("<Null:NullFlavor: NI>"))
            {
                this.setHandlingCodeEtsId(ce.code().toString());
            }
        }
    }


    /**
     * 该方法解决老权限权限报错问题,后续废弃
     * 
     * @param ce
     */
    @Deprecated
    public void setPermissionCode(CE ce)
    {
        setRimCoreEntyCdSets(ce, RIGHTSTYPECODE);
    }


    @Deprecated
    public CE getPermissionCode() throws Hl7Exception
    {
        for (RimCoreEntyCdSets entityCdSets : this.getEntyCdSetsList())
        {
            if (RIGHTSTYPECODE.toString().equals(entityCdSets.getAttributeTypeCode()))
            {
                return DataTypeUtil.getCE(entityCdSets);
            }
        }
        return null;
    }


    public CE getHandlingCode() throws Hl7Exception
    {
        if (this.getHandlingCodeEtsId().equals(HANDLINGCODE.toString()))
        {
            for (RimCoreEntyCdSets entityCdSets : this.getEntyCdSetsList())
            {
                if (this.getHandlingCodeEtsId().equals(entityCdSets.getAttributeTypeCode()))
                {
                    return DataTypeUtil.getCE(entityCdSets);
                }
            }
        }
        else
            return DataTypeUtil.getCE(this.getHandlingCodeEtsId());
        return null;
    }

    @Column(name = "DETERMINER_CODE")
    private String dmCode;
    // @Column(name="ENTITY_CODE_ETS_ID") private String entityCodeEtsId;

    @Column(name = "EXISTENCE_START_DATE_TS")
    private Timestamp existenceStartDateTs;
    @Column(name = "EXISTENCE_END_DATE_TS")
    private Timestamp existenceEndDateTs;
    @Column(name = "EXISTENCE_DATE_TXT")
    private String existenceDateTxt;
    @Column(name = "EXISTENCE_DATE_IVL_TXT")
    private String existenceDateIvlTxt;
    @Column(name = "EXISTENCE_DATE_IVL_UOM_CODE")
    private String existenceDateIvlUomCode;

    @Column(name = "RISK_CODE_ETS_ID")
    private String riskCodeEtsId = RISKCODE.toString();
    @Column(name = "HANDLING_CODE_ETS_ID")
    private String handlingCodeEtsId = HANDLINGCODE.toString();


    public void setDmCode(String dmCode)
    {
        this.dmCode = dmCode;
    }


    public String getDmCode()
    {
        return dmCode;
    }


    private void setExistenceStartDateTs(Timestamp existenceStartDateTs)
    {
        this.existenceStartDateTs = existenceStartDateTs;
    }


    private Timestamp getExistenceStartDateTs()
    {
        return existenceStartDateTs;
    }


    private void setExistenceEndDateTs(Timestamp existenceEndDateTs)
    {
        this.existenceEndDateTs = existenceEndDateTs;
    }


    private Timestamp getExistenceEndDateTs()
    {
        return existenceEndDateTs;
    }


    private void setExistenceDateTxt(String existenceDateTxt)
    {
        this.existenceDateTxt = existenceDateTxt;
    }


    @SuppressWarnings("unused")
    private String getExistenceDateTxt()
    {
        return existenceDateTxt;
    }


    private void setExistenceDateIvlTxt(String existenceDateIvlTxt)
    {
        this.existenceDateIvlTxt = existenceDateIvlTxt;
    }


    private String getExistenceDateIvlTxt()
    {
        return existenceDateIvlTxt;
    }


    private void setExistenceDateIvlUomCode(String existenceDateIvlUomCode)
    {
        this.existenceDateIvlUomCode = existenceDateIvlUomCode;
    }


    private String getExistenceDateIvlUomCode()
    {
        return existenceDateIvlUomCode;
    }


    private void setRiskCodeEtsId(String riskCodeEtsId)
    {
        this.riskCodeEtsId = riskCodeEtsId;
    }


    private String getRiskCodeEtsId()
    {
        return riskCodeEtsId;
    }


    private void setHandlingCodeEtsId(String handlingCodeEtsId)
    {
        this.handlingCodeEtsId = handlingCodeEtsId;
    }


    private String getHandlingCodeEtsId()
    {
        return handlingCodeEtsId;
    }


    // 将CE的属性值赋给RimCoreEntyCdSets
    protected RimCoreEntyCdSets convertRimCoreEntyCdSets(RimCoreEntyCdSets cdsets, CE ce)
    {
        if (ce != null)
        {
            cdsets.setCodingschemeChName(ce.codeSystemChName().isNull().booleanValue() ? null : ce.codeSystemChName().stringValue());
            cdsets.setCodingschemeEnName(ce.codeSystemEnName().isNull().booleanValue() ? null : ce.codeSystemEnName().stringValue());
            cdsets.setConceptName(ce.codeName().isNull().booleanValue() ? null : ce.codeName().stringValue());
            cdsets.setCodingschemeVersionName(ce.codeSystemVersion().isNull().booleanValue() ? null : ce.codeSystemVersion().stringValue());
            cdsets.setConceptCode(ce.code().isNull().booleanValue() ? null : ce.code().stringValue());
            cdsets.setCodingschemeOid(ce.codeSystem().isNull().booleanValue() ? null : ce.codeSystem().stringValue());
        }
        return cdsets;
    }


    // 将II的属性值赋给RimCoreEntyIi
    protected RimCoreEntyIi convertRimCoreEntyIi(RimCoreEntyIi entityii, II ii)
    {
        entityii.setRootId(ii.root().stringValue());
        entityii.setExtensionTxt(ii.extension().stringValue());
        entityii.setDisplayableFlag(ii.iiState().stringValue());
        entityii.setAssigningAuthorityNameSouce((ii.iiSouce() != null ? ii.iiSouce().stringValue() : null));

        return entityii;
    }


    protected RimCoreEds converRimCoreEds(RimCoreEds rimCoreEd, ED ed)
    {
        if (rimCoreEd == null)
        {
            rimCoreEd = new RimCoreEds();
        }
        rimCoreEd.setEdBlob(ed.integrityCheck().byteArray()); // 二进制文件
        rimCoreEd.setEdClob(ed.literal().toString().toCharArray()); // 大文本
        rimCoreEd.setMediaTypeCode(ed.mediaType().toString());
        rimCoreEd.setCharacterSetCode(ed.charset().toString());
        rimCoreEd.setLanguageCode(ed.language().toString());
        rimCoreEd.setCompressionCode(ed.compression().toString());
        rimCoreEd.setRefTelAddressTxt(ed.reference().address().toString());
        rimCoreEd.setRefTelSchemeCode(ed.reference().scheme().toString());
        if (null != ed.reference().useablePeriod().hull().low())
        {
            rimCoreEd.setRefTelStartDateTs(new Timestamp(ed.reference().useablePeriod().hull().low().toDate().getTime()));
        }
        if (null != ed.reference().useablePeriod().hull().high())
        {
            rimCoreEd.setRefTelEndDateTs(new Timestamp(ed.reference().useablePeriod().hull().high().toDate().getTime()));
        }
        rimCoreEd.setRefTelGtsTxt(ed.reference().useablePeriod().literal().toString());
        rimCoreEd.setEdRefTelUses(ed.reference().use().toSet());
        rimCoreEd.setIntegrityCheckAlgCode(ed.integrityCheckAlgorithm().toString());

        /*
         * if (!ed.integrityCheck().isNull().booleanValue()) { //次属性有问题，暂屏蔽
         * rimCoreEd.setIntegrityCheckTxt(ed.integrityCheck().stringValue()); }
         */
        return rimCoreEd;
    }


    /**
     * 
     * @Title: setRimCoreRoleCdSets
     * @Description: 根据
     * @param dicCode
     *            ce字典类型
     * @param attributeTypeCode
     *            匹配属性名称
     * @firstAuthor Obama
     * @firstTime 2011-07-01 13:14:58
     * @lastAuthor Obama
     * @lastTime 2011-07-301 13:14:58
     */
    protected void setRimCoreEntyCdSets(CE dicCode, EntityCdSetCode attributeTypeCode)
    {
        for (RimCoreEntyCdSets cdsets : getEntyCdSetsList())
        {
            if (cdsets.getAttributeTypeCode() != null && cdsets.getAttributeTypeCode().equals(attributeTypeCode.toString()))
            {
                // attributeTypeCode匹配直接更新
                convertRimCoreEntyCdSets(cdsets, dicCode);
                return;
            }
        }
        // 没有匹配新建
        RimCoreEntyCdSets rcrc = new RimCoreEntyCdSets();
        rcrc.setAttributeTypeCode(attributeTypeCode.toString());
        addEntyCdSets(convertRimCoreEntyCdSets(rcrc, dicCode));
    }


    protected RimCoreEntyCdSets getRimCoreEntyCdSets(EntityCdSetCode attributeTypeCode)
    {
        if (attributeTypeCode == null)
        {
            return null;
        }
        for (RimCoreEntyCdSets cdsets : getEntyCdSetsList())
        {
            if (cdsets.getAttributeTypeCode() != null && cdsets.getAttributeTypeCode().equals(attributeTypeCode.toString()))
            {
                return cdsets;
            }
        }
        return null;
    }


    // 获得指定identifierName类型的id
    public II getId(EntityIICode identifierName) throws Hl7Exception
    {
        if (identifierName == null)
        {
            return null;
        }
        for (RimCoreEntyIi ii : getEntyIiList())
        {
            if (identifierName.toString().equals(ii.getIdentifierName()))
            {
                return DataTypeUtil.getII(ii.getExtensionTxt(), ii.getAssigningAuthorityNameSouce(), ii.getDisplayableFlag(),
                    DataTypeUtil.getCE(ii.getRimCoreEntyCdSets()), ii.getIdentifierName());
            }
        }
        return null;
    }


    // 设置指定identifierName类型的id
    protected void setId(II id, EntityIICode identifierName)
    {
        if (identifierName == null)
        {
            return;
        }
        for (RimCoreEntyIi ii : getEntyIiList())
        {
            if (ii.getIdentifierName().equals(identifierName.toString()))
            {
                // 匹配identifierName更新entityii
                convertRimCoreEntyIi(ii, id);
                ii.setRimCoreEntyCdSets(convertRimCoreEntyCdSets(ii.getRimCoreEntyCdSets(), id.iiType()));
                ii.setLastUpdateDate(new Timestamp(new Date().getTime()));
                ii.setLastUpdatedBy(getLastUpdatedBy());
                return;
            }
        }
        // 都不匹配identifierName新建roleii
        RimCoreEntyIi entityii = new RimCoreEntyIi();

        if (id.iiType() != null && !id.iiType().isNull().booleanValue())
        {
            RimCoreEntyCdSets entyCdSets = new RimCoreEntyCdSets();
            entityii.setRimCoreEntyCdSets(convertRimCoreEntyCdSets(entyCdSets, id.iiType()));
            addEntyCdSets(entyCdSets);
        }
        entityii.setIdentifierName(identifierName.toString());

        entityii.setCreatedBy(getCreatedBy());
        entityii.setCreationDate(new Timestamp(new Date().getTime()));
        entityii.setLastUpdateDate(new Timestamp(new Date().getTime()));
        entityii.setLastUpdatedBy(getLastUpdatedBy());
        addEntyIi(convertRimCoreEntyIi(entityii, id));
    }


    public void setRightsTypeCode(CE ce)
    {
        setRimCoreEntyCdSets(ce, RIGHTSTYPECODE);
    }


    public CE getRightsTypeCode()
    {
        return DataTypeUtil.getCE(getRimCoreEntyCdSets(RIGHTSTYPECODE));
    }

}
